#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>
#include <vector>
#include <ctime>
#include "Task.hpp"
using namespace std;

#define PROCESS_NUM 5

int waitCommand(int waitfd, bool &quit){
    uint32_t command = 0;           // 指定为四字节数据
    ssize_t s = read(waitfd, &command, sizeof(command));
    if(s == 0){
        quit = true;
        return -1;
    }
    assert(s == sizeof(uint32_t));
    return command;
}

void SendAndWakeUp(pid_t who, int fd, uint32_t command){
    write(fd, &command, sizeof(command));
    cout << "call process[ " << who << " ] execute : " << desc[command] << "through : " << fd << endl;
}



int main(){
    load();


    // pid 和 pipefd 的键值对
    vector<pair<pid_t, int>> slots;

    // 创建多个进程
    for(int i = 0;i<PROCESS_NUM;i++){
        int pipefd[2] = {0};
        // 创建管道
        int n = pipe(pipefd);
        assert(n == 0);
        (void)n;


        pid_t id = fork();
        assert(id != -1);

        // 子进程只读取

        if(id == 0){
            // 子进程
            close(pipefd[1]);
            while(true){
                // 等指令
                bool quit = false;
                int command = waitCommand(pipefd[0], quit);     // 如果不发就阻塞等待 
                if(quit) break;
                // 执行命令
                if(command >= 0 && command < HandlertaskSize()){
                    callBack[command]();
                }else{
                    cout << "非法 command：" << command << endl;
                }
            }
            exit(1);

        }
        // 父进程
        // 父进程写入
        close(pipefd[0]);
        slots.push_back(pair<pid_t, int>(id, pipefd[1]));

    }


    // 开始任务
    // 派发任务
    srand((unsigned)time(nullptr)^getpid()^0x4561);
    while(true){
        int comd = rand()% HandlertaskSize();
        // 随机数的方式实现负载均衡
        int select = rand() % slots.size();
        SendAndWakeUp(slots[select].first, slots[select].second, comd);
        sleep(1);

#if 0
        int comd;
        int select;
        cout << "=================================================================="<<endl;
        cout << "\t\t => 1. show function\t 2. send command" << endl;
        cout << "=================================================================="<<endl;
        cout << "Please select > ";
        cin >> select;
        if(select == 1) showHandler();
        else if(select == 2){
            cout << "Enter your Command > ";
            // 选择任务
            cin >> comd;
            // 选择进程
            int proc = rand()%slots.size();
            // 布置任务
            SendAndWakeUp(slots[proc].first, slots[proc].second, comd);
        }
        else{
            cout << "输入有误！" << endl;
        }
#endif

    }


    // 关闭 fd，结束所有进程
    for(const auto &slot : slots){
        close(slot.second);
    }
    for(const auto &slot : slots){
        waitpid(slot.first, nullptr, 0);
    }
    return 0;
}